package com.fc.test.controller.gen;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.fc.test.model.auto.ItemCase;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.PageInfo;
import com.fc.test.common.base.BaseController;
import com.fc.test.common.domain.AjaxResult;
import com.fc.test.model.auto.ItemList;
import com.fc.test.model.custom.TableSplitResult;
import com.fc.test.model.custom.Tablepar;
import com.fc.test.model.custom.TitleVo;
import com.fc.test.service.ItemListService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Api(value = "办事指南")
@Controller
@RequestMapping("/ItemListController")
@ApiIgnore
public class ItemListController extends BaseController{
	
	private String prefix = "gen/itemList";
	@Autowired
	private ItemListService itemListService;
	
	/**
	 * 分页跳转
	 */
	@ApiOperation(value = "分页跳转", notes = "分页跳转")
	@GetMapping("/view")
	@RequiresPermissions("gen:itemList:view")
    public String view(ModelMap model)
    {	
		String str="";
		setTitle(model, new TitleVo("列表", str+"管理", true,"欢迎进入"+str+"页面", true, false));
        return prefix + "/list";
    }
	
	/**
	 * 分页查询
	 */
	//@Log(title = "集合查询", action = "111")
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@PostMapping("/list")
	@RequiresPermissions("gen:itemList:list")
	@ResponseBody
	public Object list(Tablepar tablepar,String searchText){
		PageInfo<ItemList> page=itemListService.list(tablepar,searchText) ; 
		TableSplitResult<ItemList> result=new TableSplitResult<ItemList>(page.getPageNum(), page.getTotal(), page.getList()); 
		return  result;
	}
	
	/**
     * 新增跳转
     */
    @ApiOperation(value = "新增跳转", notes = "新增跳转")
    @GetMapping("/add")
    public String add(ModelMap modelMap)
    {
        return prefix + "/add";
    }
	
	/**
     * 新增
     */
	//@Log(title = "新增", action = "111")
   	@ApiOperation(value = "新增", notes = "新增")
	@PostMapping("/add")
	@RequiresPermissions("gen:itemList:add")
	@ResponseBody
	public AjaxResult add(ItemList itemList){
		int b=itemListService.insertSelective(itemList);
		if(b>0){
			return success();
		}else{
			return error();
		}
	}
	
	/**
	 * 删除
	 * @param ids
	 * @return
	 */
	//@Log(title = "删除", action = "111")
	@ApiOperation(value = "删除", notes = "删除")
	@PostMapping("/remove")
	@RequiresPermissions("gen:itemList:remove")
	@ResponseBody
	public AjaxResult remove(String ids){
		int b=itemListService.deleteByPrimaryKey(ids);
		if(b>0){
			return success();
		}else{
			return error();
		}
	}
	
	/**
	 * 检查Name
	 * @param itemList
	 * @return
	 */
	@ApiOperation(value = "检查Name唯一", notes = "检查Name唯一")
	@PostMapping("/checkNameUnique")
	@ResponseBody
	public int checkNameUnique(ItemList itemList){
		int b=itemListService.checkNameUnique(itemList);
		if(b>0){
			return 1;
		}else{
			return 0;
		}
	}
	
	
	/**
	 * 修改跳转
	 * @param id
	 * @param mmap
	 * @return
	 */
	@ApiOperation(value = "修改跳转", notes = "修改跳转")
	@GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("ItemList", itemListService.selectByPrimaryKey(id));

        return prefix + "/edit";
    }
	
	/**
     * 修改保存
     */
    //@Log(title = "修改", action = "111")
    @ApiOperation(value = "修改保存", notes = "修改保存")
    @RequiresPermissions("gen:itemList:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ItemList record)
    {
        return toAjax(itemListService.updateByPrimaryKeySelective(record));
    }

    
    /**
   	 * 根据主键查询
   	 * 
   	 * @param id
   	 * @param mmap
   	 * @return
   	 */
   	@ApiOperation(value = "根据id查询唯一", notes = "根据id查询唯一")
   	@PostMapping("/get/{id}")
   	public ItemList edit(@PathVariable("id") String id) {
   		return itemListService.selectByPrimaryKey(id);
   	}



	/**
	 * 导入文件跳转页面
	 * @return
	 * @author fuce
	 * @Date 2019年11月20日 下午10:19:03
	 */
	@ApiOperation(value = "导入跳转", notes = "导入跳转")
	@GetMapping("/importExcel")
	public String importExcel(ModelMap modelMap)
	{
		return prefix + "/importExcel";
	}


	/**
	 * 文件上传
	 * @param file
	 * @return
	 * @author fuce
	 * @Date 2019年11月20日 下午10:18:49
	 */
	//@Log(title = "文件上传", action = "1")
	@ApiOperation(value = "读取excel", notes = "读取excel")
	@PostMapping("/readExcel")
	@ResponseBody
	public AjaxResult updateAvatar(@RequestParam("file") MultipartFile file)
	{
		try
		{
			if (!file.isEmpty())
			{

				System.out.println(file.getBytes().length);
				ImportParams params = new ImportParams();
				//以下两个属性 设置不对  无法获取数据 都是null
				params.setTitleRows(1);//表的标题占用一行
				params.setHeadRows(1);//对接的列字段名   占用一行
				params.setNeedVerify(Boolean.TRUE);
				List<ItemList> list = ExcelImportUtil.importExcel(file.getInputStream(), ItemList.class, params);

				itemListService.batchInsert(list);

				return AjaxResult.successData(200, "添加数量："+list.size());

			}
			return error();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return error(e.getMessage());
		}
	}


	/**
	 *
	 * @param response
	 * @throws Exception
	 */
	@ApiOperation(value = "下载文件模版", notes = "下载文件模版")
	@GetMapping("/download")
	public void downloadLocal(HttpServletResponse response) throws Exception {
		// 下载本地文件
		ClassPathResource resource = new ClassPathResource("\\static\\download\\东亭街道为民服务中心事项清单_模板.xlsx");
		// 读到流中
		InputStream inStream =resource.getInputStream();// 文件的存放路径
		// 设置输出的格式
		response.reset();
		response.setContentType("application/octet-stream");
		response.addHeader("Content-Disposition", "attachment; filename=\"" +  URLEncoder.encode("东亭街道为民服务中心事项清单_模板.xlsx", "utf-8") + "\"");
		// 循环取出流中的数据
		byte[] b = new byte[1000];
		int len;
		try {
			while ((len = inStream.read(b)) > 0)
				response.getOutputStream().write(b, 0, len);
			inStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
